package wsi.dataguide;

import java.io.File;
import java.util.Map;
import java.util.Map.Entry;

import org.rygh.core.util.UIo;
import org.rygh.semantic.gui.swing.input.Input;

import wsi.function.DirManager;
import wsi.function.Function.Phrase;
import wsi.script.AppXml;
import wsi.task.TaskRoutine;

public class DataGuideBuilder extends TaskRoutine {

	private final DataGuide dataGuide = new DataGuide();

	public DataGuideBuilder(DirManager dir) {
		super(dir);

	}

	@Override
	public void compute() {
		// build according to inputs.

		Map<Input, File> xmls = dir.getFileMap();

		if (xmls == null) {
			log.info("[error] no xml files.");
			return;
		}

		DataGuideParser parser;

		for (Entry<Input, File> e : xmls.entrySet()) {
			// log.info("parsing " + f.getName());
			File f = e.getValue();

			String xml = UIo.readFile(f);

			if (xml.isEmpty()) {
				log.info(String.format("Empty XML document for %s", f.getName()));
				continue;
			}

			parser = new DataGuideParser(e.getKey(), xml, dataGuide);
			parser.parse();

			dataGuide.updateOccurrence();
			dataGuide.clear();

			// System.out.println(dataGuide);

			if (function.isSkipped(Phrase.REST)) {
				log.info("break for trial.");
				break;
			}
		}
	}

	public DataGuide getDataGuide() {
		return dataGuide;
	}

	@Override
	public String save() {
		String full_concise, full, _10, _empty;

		_empty = dataGuide.toString(0);

		if (AppXml.__DEBUG) {
			full_concise = dataGuide.toString(-1);
			full = dataGuide.toString(Integer.MAX_VALUE);
			_10 = dataGuide.toString(10);

			// when debug is off, transfer dg in memory.

			UIo.saveFile(new File(dir.getDebugDir(), "_debug_dg_concise.xml"),
					full_concise);
			UIo.saveFile(new File(dir.getDebugDir(), "_debug_dg_10.xml"), _10);
			UIo.saveFile(new File(dir.getDebugDir(),
					DirManager.DATA_GUIDE_WITH_VALUES), full);
		}

		UIo.saveFile(new File(dir.getFunctionDir(),
				DirManager.DATA_GUIDE_SCHEMA), _empty);

		return _empty;
	}
}
